<?php

class StudentController extends AppController
{
    # Controller Name to be used
    var $name = 'Student';

    # Models to be used
    var $uses = array(
        'StudentUser',
        'Fee',
        'Config',
        'FeeType',
        'Transaction',
        'TransactionItem',
        'StudentNotification',
        'Program',
        'StudentServiceRequest',
        'AcademicSession',
        'ForgotPassToken',
        'StudentSrcDue',
        'ServiceCharge'
    );

    # set the layout to use
    var $layout = 'student_layout';


    function __validateLoginStatus()
    {
        //debug($this->Session->read('loginData'));
        if ($this->params['action'] != 'login' && $this->params['action'] != 'logout' && $this->params['action'] != 'forgot_password' && $this->params['action'] != 'reset_password') {
            if ($this->Session->check('loginData') == false) {
                $this->redirect(array('action' => 'login?ref=' . $this->params['action']));
            } else {
                $auth_user = $this->Session->read('loginData');
                //check if the user has not done multiple login
                $db_login_session = $this->getLoginSession($auth_user['id']);
                $login_session = $auth_user['login_session'];
                if ($db_login_session != $login_session) {
                    $this->Session->setFlash('Your session has expired!');
                    $this->redirect(array('action' => 'logout'));
                }
                //authorize the user, if the user is not authorized to view this page then redirect them to their session
                //$auth_user = $this->Session->read('loginData');
                if ($auth_user['user_type'] != 'student_user') {
                    if ($auth_user['user_type'] == 'staff_user') {
                        $this->redirect(array('controller' => 'Staff', 'action' => 'index'));
                    } elseif ($auth_user['user_type'] == 'bank_user') {
                        $this->redirect(array('controller' => 'Bank', 'action' => 'index'));
                    } else {
                        $this->redirect(array('action' => 'logout'));
                    }
                }
            }
        }
    }

    function __enforcePasswordChange()
    {
        //debug($this->Session->read('loginData'));
        if ($this->params['action'] != 'editprofile' && $this->params['action'] != 'login' && $this->params['action'] != 'logout' && $this->params['action'] != 'forgot_password' && $this->params['action'] != 'reset_password') {
            if ($this->Session->check('loginData') == false) {
                $this->redirect(array('action' => 'login?ref=' . $this->params['action']));
            } else {
                $auth_user = $this->Session->read('loginData');
                if ($auth_user['first_time_pass_changed'] == 'No') {
                    $this->redirect(array('action' => 'editprofile'));
                }
            }
        }
    }

    private function getLoginSession($user_id)
    {
        $data = $this->StudentUser->find('first', array(
            'conditions' => array('id' => $user_id),
            'recursive' => -1
        ));
        return $data['StudentUser']['login_session'];
    }

    function  beforeFilter()
    {
        parent::beforeFilter();
        $this->__validateLoginStatus();
        $this->__enforcePasswordChange();
        $credit_bal = $this->_getAccBal();
        //debug($cart);

        $this->set('credit_bal_money', $this->formatNumber($credit_bal, 'money'));
        $this->set('credit_bal_number', $this->formatNumber($credit_bal));
    }


    public function login()
    {
        if ($this->request->is('post')) {
            $logme  = $this->request->data['StudentUser'];
            $logme = $this->StudentUser->sanitize($logme);
            $result = $this->StudentUser->login($logme['username'], $logme['password']);
            //exit;
            if ($result['status']) {
                //start a new session for this user
                $loginData = $this->createLoginSession($result['data']['StudentUser']);
                //write data to session
                $this->Session->write('loginData', $loginData);

                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->write('msg_type', 'error');
                $this->Session->setFlash($result['msg']);
            }
        }

        $this->layout = 'login_layout';
    }

    private function createLoginSession($data)
    {
        $login_session = $this->randomString(50);
        $data['login_session'] = $login_session;
        $this->StudentUser->save(array(
            'id' => $data['id'],
            'login_session' => $login_session
        ));
        return $data;
    }

    public function logout()
    {
        $this->Session->delete('loginData');
        $this->Session->destroy();
        $this->redirect(array('action' => 'login'));
    }


    # Controller actions
    /**
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index()
    {
        $notifications = $this->getNotification();
        $auth_user = $this->Session->read('loginData');
        $this->set('title_for_layout', 'Dashboard');
        $this->set(compact('page_title', 'notifications'));
    }

    function getNotification()
    {
        $auth_user = $this->Session->read('loginData');
        $user_id = $auth_user['id'];
        $notifications = $this->StudentNotification->find('all', array(
            'conditions' => array('StudentNotification.student_user_id' => $user_id, 'StudentNotification.deleted' => 'n'),
            'recursive' => -1
        ));
        return $notifications;
    }


    function deleteNotification($id = null)
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            //we flag the notification as deleted as we don't need them any more
            $this->StudentNotification->save(array(
                    'id' => $id,
                    'deleted' => 'y'
                )
            );
            //$this->StudentNotification->deleteAll(array('StudentNotification.id' => $id), false);
        }
    }


    function editprofile()
    {
        $auth_user = $this->Session->read('loginData');
        if ($this->request->is('post')) {
            $error = false;
            //Check if the student is trying to use the same pass as the date of birth , then reject
            if (trim($this->request->data['StudentUser']['password']) == $auth_user['date_of_birth']) {
                $error = true;
                $this->Session->setFlash("Password Error, You can't use your default password as a new password. ");
            }

            if ($this->request->data['StudentUser']['password']) {
                //echo 'yes';
                $this->request->data['StudentUser']['password'] = md5(trim($this->request->data['StudentUser']['password']));
                if ($auth_user['first_time_pass_changed'] == 'No') {
                    $this->request->data['StudentUser']['first_time_pass_changed'] = 'Yes';
                }
            } else {
                $auth_user = $this->Session->read('loginData');
                $this->request->data['StudentUser']['password'] = $auth_user['password'];
            }
            if ($this->request->data['StudentUser']['cellphone']) {
                $cell = $this->request->data['StudentUser']['cellphone'];
                $this->request->data['StudentUser']['cellphone'] = preg_replace('/-/', '', $cell);
            }

            if ($error) {
                $this->Session->write('process_error', 'yes');
            } else {
                $result = $this->StudentUser->save($this->request->data);

                if ($result) {
                    //write data to session
                    $user = $this->StudentUser->getUserById($this->request->data['StudentUser']['id']);
                    $this->Session->write('loginData', $user['StudentUser']);
                    $this->Session->setFlash('Your profile info has been updated !');
                    $this->Session->write('process_error', 'no');
                    $msg = "Dear " . $auth_user['fname'] . " your upsa account profile has been updated.";
                    //$msg = 'Your have successfully paid GHS'.$total_paying.'. as fees for '.$this->current_academic_year.' academic year.';

                    $fon_number = $this->request->data['StudentUser']['cellphone'];
                    $this->Message->sendSMS($msg, $fon_number);
                } else {
                    $this->Session->setFlash('Sorry, your profile info could not be updated');
                    $this->Session->write('process_error', 'yes');
                }
            }

            $this->redirect(array('action' => 'editprofile'));
        }

        $profile = $this->StudentUser->getUserById($auth_user['id'], -1);
        $profile = $profile['StudentUser'];
        $config = $this->config;
        $edit_other_profile = $config['students_can_edit_other_profile'];
        $pro = $this->Program->find('all', array(
            'fields' => array('id', 'progid', 'short_name'),
            //'conditions'=>array('deleted'=>'n'),
            'recursive' => -1
        ));
        $programs = array();
        foreach ($pro as $p) {
            $programs[$p['Program']['id']] = $p['Program']['progid'];
        }
        $classification = array();
        foreach ($this->classification as $c) {
            $classification[$c] = $c;
        }

        $levels = array();
        foreach ($this->levels as $l) {
            $levels[$l] = $l;
        }

        $countries = array();
        foreach ($this->countries as $l) {
            $countries[$l] = $l;
        }
        $controller = $this;
        $this->set(compact('controller', 'profile', 'edit_other_profile', 'countries', 'levels', 'classification', 'programs'));
    }


    public function history()
    {
        $auth_user = $this->Session->read('loginData');
        $user_id = $auth_user['id'];

        $this->paginate = array(
            'TransactionItem' => array(
                'conditions' => array('Transaction.student_user_id' => $user_id),
                'contain' => array('Transaction' => array('AcademicSession'), 'Fee' => array('FeeType')),
                'order' => array('TransactionItem.id' => 'desc'),
                'limit' => 10
            )
        );
        $transactData_data = $this->paginate('TransactionItem');
        $controller = $this;
        $transactData = $hold = array();
        foreach($transactData_data as $key => $t){
            $type = $t['TransactionItem']['desc'];
            if($type == 'Service Charge'){
                $hold[] = $t;
            }
            else{
                if(empty($hold)){
                    $transactData[] = $t;
                }
                else{
                    $credit = 0.00;
                    foreach($hold as $h){
                        $credit = $credit + doubleval($h['TransactionItem']['credit_amt']);
                    }
                    $h['TransactionItem']['credit_amt'] = $credit;
                    $transactData[] = $h;
                    $transactData[] = $t;
                    $hold = array();
                }
            }

        }
        //debug($transactData_data);

        $this->set('title_for_layout', 'Transaction History');
        $this->set(compact('page_title', 'transactData', 'controller'));
    }

    public function print_history()
    {
        $auth_user = $this->Session->read('loginData');
        $user_id = $auth_user['id'];
        $program_id = $auth_user['program_id'];

        $transactData = $this->TransactionItem->find('all', array(
            'conditions' => array('Transaction.student_user_id' => $user_id),
            'contain' => array('Transaction' => array('AcademicSession'), 'Fee' => array('FeeType')),
            'order' => array('TransactionItem.id' => 'desc'),
            'recursive' => 2
        ));

        $program = $this->Program->find('first', array(
            'conditions' => array('id' => $program_id),
            'recursive' => -1
        ));

        $this->layout = 'print_layout';
        $print_title = 'Transaction History';
        $controller = $this;
        $this->set(compact('transactData', 'print_title', 'controller', 'auth_user', 'program'));
    }


    public function payments()
    {
        $auth_user = $this->Session->read('loginData');

        $cart = $this->_getBills($auth_user['index_number']);

        //$msg = 'Testing sms';
        //$fon_number = "233243569192";
        //$res = $this->Message->sendSMS($msg, $fon_number);
        $charge_amount = doubleval($this->config['service_charge']) * 100;
        $current_acca_year = $this->current_academic_year;
        $this->set('title_for_layout', 'Payments');
        $this->set(compact('cart', 'current_acca_year','charge_amount'));
    }

    function _getBills($index_number)
    {
        return $this->StudentUser->getBills($index_number, $this->current_academic_year);
    }


    function _getAccBal()
    {
        $auth_user = $this->Session->read('loginData');
        $user_id = $auth_user['id'];

        $data = $this->StudentUser->find('first', array(
            'conditions' => array('StudentUser.id' => $user_id),
            'recursive' => -1
        ));
        $credit_bal = 0.00;
        if ($data) {
            $credit_bal = doubleval($data['StudentUser']['account_balance']);
        }
        return $credit_bal;
    }


    function _getServiceBill($value = 0){
        $charge_amount = doubleval($this->config['service_charge']);
        $type = $this->config['service_charge_type'];
        if($type == 'percent fee'){
            $r = $value * $charge_amount;
            $s = $this->formatNumber($r,'number',2);
            return $s;
        }
        else{
            return $charge_amount;
        }
    }

    function _payServiceBill($user_id,$program_id,$level,$classification,$ser_amt){
        /*** For Now Store Charges only , this will be used to generate bills at the end of the month. **/
        $academic_session_id =  $this->Config->get('academic_session_id');
        $cis_cut =  doubleval($this->Config->get('cis_cut'));
        //$upsa_cut =  doubleval($this->Config->get('upsa_cut'));
        $dev_cut =  doubleval($this->Config->get('dev_cut'));
        $total_amount = doubleval($ser_amt);
        $cis_total_amt = $cis_cut * $total_amount;
        $upsa_amt =  $total_amount - $cis_total_amt;
        //$dev_amt = $dev_cut * $cis_total_amt;
        //$cis_amt = $cis_total_amt - $dev_amt;
        /*$save = array(
            'Transaction' => array(
                'trans_ref_no' => "CRA" . $this->Transaction->getNextAutoIncrement() . "001",
                'trans_type' => 'service_charge',
                'student_user_id' => $user_id,
                'program_id' => $program_id,
                'level' => $level,
                'classification' => $classification,
                'academic_session_id' => $academic_session_id,
                'ip_address' => $_SERVER['REMOTE_ADDR'],
            ),
            'TransactionItem' => array(
                array(
                    'trans_currency' => 'GHS',
                    'credit_amt' => $cis_total_amt,
                    'desc' => "Service Charge",
                    'actual_trans_type' => 'service_charge'
                ),
                 array(
                     'trans_currency' => 'GHS',
                     'credit_amt' => $upsa_amt,
                     'desc' => "Service Charge",
                     'actual_trans_type' => 'service_charge_upsa'
                 )
            )
        );*/
        $res = false;
       /* if($this->Transaction->saveAll($save)){
            $save2 = array(
                'ServiceCharge' => array(
                    'transaction_id' => $this->Transaction->id,
                    'academic_session_id' => $academic_session_id,
                    'amount' => $ser_amt,
                    'cis_amt' => $cis_total_amt,
                    'upsa_amt' => $upsa_amt,
                    'dev_amt' => 0.00,
                )
            );
            $this->ServiceCharge->save($save2);
            $res = true;
        }*/
        $save2 = array(
            'ServiceCharge' => array(
                'transaction_id' => $this->Transaction->id,
                'academic_session_id' => $academic_session_id,
                'amount' => $ser_amt,
                'cis_amt' => $cis_total_amt,
                'upsa_amt' => $upsa_amt,
                'dev_amt' => 0.00,
                'payment_form' => 'invoice'
            )
        );
        if($this->ServiceCharge->save($save2)){
            $res = true;
        };

        return $res;
    }


    function do_payment()
    {
        if ($this->request->is('ajax')) {
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;

            $auth_user = $this->Session->read('loginData');
            $user_id = $auth_user['id'];
            $program_id = $auth_user['program_id'];
            $level = $auth_user['level'];
            $classification = $auth_user['classification'];

            $pdata = json_decode($_POST['data'], true);

            $trans_details = $fee_transactions = array();
            $fee_ids_arr = array();
            $total_paying = 0.00;
            $total_to_charge = 0.00;
            foreach ($pdata as $key => $value) {
                $desc = 'Fee Payment';
                if ($value['trans_type_to_use'] == 'item_purchase') {
                    $desc = 'Item Purchase';
                }
                elseif($value['trans_type_to_use'] == 'service_charge'){
                    $desc = 'Service Charge Arrears';
                }
                $fee_type_id = $value['fee_type_id'];
               /* if($fee_type_id == 24){//Service charge arrears

                }*/
                $trans_details[] = array(
                    'fee_id' => $key,
                    'trans_currency' => 'GHS',
                    'credit_amt' => $value['amount'],
                    'desc' => $desc,
                    'actual_trans_type' => $value['trans_type_to_use']
                );
                $fee_transactions[$key] = array(
                    'credit_amt' => $value['amount']
                );
                $fee_ids_arr[] = $key;
                //Exempt biill types that should not be charged 1 %
                if(!in_array($fee_type_id,array('24'))){
                    $total_to_charge = $total_to_charge + doubleval($value['amount']);
                }
                $total_paying = $total_paying + doubleval($value['amount']);
            }

            //validate
            $fees_to_pay = $this->Fee->find('all', array(
                'conditions' => array('Fee.id' => $fee_ids_arr),
                'contain' => array(
                    'TransactionItem' => array(
                        'fields' => array('TransactionItem.id', 'TransactionItem.credit_amt')
                    ),
                    'FeeType' => array(
                        'fields' => array('FeeType.id', 'FeeType.fee_category', 'FeeType.description')
                    )
                ),
                'recursive' => 1
            ));

            $total_owed = 0.00;
            $total_paid = 0.00;
            $paying_errors = array();
            foreach ($fees_to_pay as $fee) {
                $fee_amount = doubleval($fee['Fee']['amount']);
                $feeid = $fee['Fee']['id'];
                $fee_category = $fee['FeeType']['fee_category'];
                $description = $fee['FeeType']['description'];
                $paid = 0.00;
                $owed = 0.00;
                $trans_items = $fee['TransactionItem'];
                foreach ($trans_items as $tran) {
                    $paid = $paid + doubleval($tran['credit_amt']);
                }
                $owed = $fee_amount - $paid;
                //Totals
                $total_paid = $total_paid + $paid;
                $total_owed = $total_owed + $owed;

                //validate overpayments and underpayments
                if ($fee_category != 'Fees') {
                    $incoming_payment = $fee_transactions[$feeid]['credit_amt'];
                    if ($owed == $fee_amount) {
                        $overall_tobe_payment = $incoming_payment + $paid;
                    } elseif ($owed < $fee_amount) {
                        $overall_tobe_payment = $incoming_payment;
                    }

                    if ($overall_tobe_payment > $owed) {
                        $paying_errors[$description] = "You can't overpay what you owe for ";
                    } elseif ($overall_tobe_payment < $owed) {
                        $paying_errors[$description] = "You can't underpay what you owe for ";
                    }
                }
            }

            $acct_balance = $this->_getAccBal();

            //Check if Amount paying is more than Credit amount
            if ($total_paying > $acct_balance) {
                return json_encode(array('code' => 1, 'mesg' => __("You don't have enough credit for this payment.")));
            }

            /******* Service Charge Validation  ****/
            $charge_amount = doubleval($this->config['service_charge']) * 100;
            $ser_amt = $this->_getServiceBill($total_to_charge);

            /* $t_paying = $total_paying + $ser_amt;
             if ($t_paying > $acct_balance) {
                 return json_encode(array('code' => 1, 'mesg' => __("You don't have enough credit to cover for this payment and the transactional cost of $charge_amount %.")));
             }*/

            /*//Check if the student is overpaying and underpayments
            if($total_paying > $total_owed){
                return json_encode(array('code' => 1, 'mesg' => __("You can't over pay your fees.")));
            }*/
            if (!empty($paying_errors)) {
                $msg = "";
                foreach ($paying_errors as $k => $v) {
                    $msg .= $v . " " . $k . "\n";
                }
                return json_encode(array('code' => 1, 'mesg' => $msg));
            }


            $save = array(
                'Transaction' => array(
                    'trans_ref_no' => "CRA" . $this->Transaction->getNextAutoIncrement() . "001",
                    'trans_type' => 'fee_payment',
                    'student_user_id' => $user_id,
                    'program_id' => $program_id,
                    'level' => $level,
                    'classification' => $classification,
                    'academic_session_id' => $this->Config->get('academic_session_id'),
                    'ip_address' => $_SERVER['REMOTE_ADDR'],
                ),
                'TransactionItem' => $trans_details
            );

            if ($this->Transaction->saveAll($save)) {

                //Create service charge transaction.
                $this->_payServiceBill($user_id,$program_id,$level,$classification,$ser_amt);
               // $total_paying = $total_paying + $ser_amt;
                $this->StudentUser->debitAccount($user_id, $total_paying);
                $bal = doubleval($auth_user['account_balance']) - $total_paying;
                $msg = "Dear " . $auth_user['fname'] . " you have successfully paid a fee of GHS " . $total_paying . " and your acct. bal. is GHS " . $bal;
                //$msg = 'Your have successfully paid GHS'.$total_paying.'. as fees for '.$this->current_academic_year.' academic year.';
                $loginData = $this->StudentUser->getUserById($user_id);
                $this->Session->write('loginData', $loginData['StudentUser']);

                $fon_number = $auth_user['cellphone'];
                $this->Message->sendSMS($msg, $fon_number);

                $this->Session->setFlash('Your selected fees have successfully been paid!');

                return json_encode(array('code' => 0, 'data' => $save, 'mesg' => __('Data Saved')));
            } else {

                return json_encode(array('code' => 1, 'mesg' => __('Sorry your fees cannot be paid!')));
            }

        }
    }


    public function order()
    {
        $auth_user = $this->Session->read('loginData');

        if ($this->request->is('ajax')) {
            $this->autoLayout = false;
            $this->autoRender = false;
            $data = json_decode($_POST['data'], true);
            $save = array();
            foreach ($data['Fee'] as $fee) {
                $fee['created_by'] = $auth_user['id'];
                $save['Fee'][] = $fee;
            }
            $save_re = $this->Fee->saveAll($this->Fee->sanitize($save['Fee']));
            if ($save_re) {
                $inserted_ids = $this->Fee->getInsertedIds();
                $sub_save = array();
                foreach ($inserted_ids as $fee_id) {
                    $sub_save['StudentServiceRequest'][] = array(
                        'fee_id' => $fee_id,
                        'student_user_id' => $auth_user['id'],
                        'academic_session_id' => $this->current_academic_session_id,
                        'created_by' => $auth_user['id']
                    );
                }
                $this->StudentServiceRequest->saveAll($this->StudentServiceRequest->sanitize($sub_save['StudentServiceRequest']));
            } else {
                $save_re = false;
            }

            if ($save_re) {
                return json_encode(array('code' => 0, 'msg' => 'You have been billed successfully, please go to payments and pay for the bills. '));
            } else {
                return json_encode(array('code' => 1, 'msg' => 'Sorry we cannot bill you now, please try again later'));
            }
        }

        $fee_types_data = $this->FeeType->find('all', array(
            //'fields'=>array('FeeType.id','FeeType.description'),
            'conditions' => array('FeeType.deleted' => 'n', 'FeeType.fee_category' => 'Conditional Fees'),
            'order' => array('FeeType.description' => 'asc'),
            'recursive' => -1
        ));
        $fee_types = array();
        $gbl_fee_type = array();
        foreach ($fee_types_data as $dt) {
            $fee_types[$dt['FeeType']['id']] = $dt['FeeType']['description'];
            $gbl_fee_type[$dt['FeeType']['id']] = $dt['FeeType'];
        }
        $current_academic_year = $this->current_academic_year;

        $this->set(compact('cart', 'fee_types', 'gbl_fee_type', 'auth_user', 'current_academic_year'));
    }


    function forgot_password()
    {
        if ($this->request->is('post')) {
            $logme  = $this->request->data['StudentUser'];
            $logme = $this->StudentUser->sanitize($logme);
            $result = $this->StudentUser->verify_account($logme['username'], $logme['email'],$logme['cellphone']);
            //exit;
            if ($result['status']) {
                //Create Token ans send email
                $stu = $result['data']['StudentUser'];
                // debug($stu);
                $length = 20;
                $token = $stu['id'] . '|' . $stu['username'] . '|' . $this->randomString($length);
                $ip = $_SERVER['REMOTE_ADDR'];
                $save = array(
                    'student_user_id' => $stu['id'],
                    'ip' => $ip,
                    'token' => $token
                );
                //Save token and send email
                $s = $this->ForgotPassToken->save($save);
                $root_to_folder = Router::url('/', true);

                if ($s) {
                    $this->redirect('reset_password/' . $token);
                    /* $mail_msg = "To reset you password please click the link below <br /> <b><a target='_blank' href='$root_to_folder/Student/reset_password/$token'>Click here to reset your password.</a></b>";
                     $emailData = array('content' => $mail_msg, 'lname' => $stu['lname'], 'fname' =>$stu['fname']);
                     $dataObj = array(
                         'data' => $emailData,
                         'render_element' => '/Emails/html/reset_password',
                     );
                     $title = 'Reset Password';
                     $this->autoRender = false;
                     $this->autoLayout = false;
                     $this->Emailer->send($this, $stu['email'], $dataObj, $title);
                     $this->Session->write('msg_type', 'success');
                     $this->Session->setFlash("An email has been sent to your email address containing the password reset link.");
                     $this->redirect(array('action'=>'login'));*/
                } else {
                    $this->Session->setFlash("Sorry can't create token. Please try again. ");
                }
            } else {
                $this->Session->setFlash($result['msg']);
            }
        }

        $this->layout = 'login_layout';
        $this->set(compact(''));
    }

    function reset_password($token = null)
    {
        if ($this->request->is('post')) {
            $this->request->data['StudentUser']['password'] = md5(trim($this->request->data['StudentUser']['password']));
            $result = $this->StudentUser->save($this->request->data);
            if ($result) {
                $token_data = array(
                    'id' => $this->request->data['StudentUser']['token_id'],
                    'used' => 'Yes'
                );
                $this->ForgotPassToken->update_token($token_data);
                $this->Session->write('msg_type', 'success');
                $this->Session->setFlash("Password has been reset. You can login with your new password");
                $this->redirect(array('action' => 'login'));
            } else {
                $this->Session->write('msg_type', 'error');
                $this->Session->setFlash("Password cannot be reset.");
            }
        }

        //verify token
        $status = $this->ForgotPassToken->verify_token($token);

        $this->layout = 'login_layout';
        $this->set(compact('status'));
    }


    function report()
    {
        $auth_user = $this->Session->read('loginData');
        if ($auth_user['user_level'] != 'SRC') { //For SRC Only
            $this->redirect(array('controller' => 'Student', 'action' => 'index'));
        }

        $start_dt = $default_start_dt = date('Y-m-01');
        $end_dt = $default_end_dt = date('Y-m-t');
        // $program_id = 6; //ACCA-UK
        $index_number = '';
        $aca_ses = $this->current_academic_session_id;
        if ($this->request->is('post')) {
            $p_data = $this->request['data']['Query'];
            $p_data = $this->StudentUser->sanitize($p_data);
            $start_dt = $default_start_dt = $p_data['start_dt'];
            $end_dt = $default_end_dt = $p_data['end_dt'];
            //$program_id = $p_data['program_id'];
            $index_number = $p_data['index_number'];
            $aca_ses = $p_data['academic_session'];
        }
        $index_number = trim($index_number);
        $index_number_p = $index_number;
        if (empty($index_number)) {
            $index_number_p = null;
        }

        //Get students ids with filters
        /* $conditions = array('StudentUser.program_id'=>$program_id);
         $stu_list = $this->StudentUser->find('all',array(
             'fields'=>array('StudentUser.id','StudentUser.index_number','StudentUser.program_id'),
             'conditions'=>$conditions,
             'recursive'=>-1
         ));
         $student_user_ids = array();
         foreach($stu_list as $dt){
             $student_user_ids[]=$dt['StudentUser']['id'];
         }*/
        $fee_type_id = 18; //SRC dues only

        $data_table = $this->_get_src_payments($start_dt, $end_dt, $fee_type_id, $aca_ses, $index_number_p);

        $academic_sessions = $this->getAcademicSessions();

        $controller = $this;

        $this->set(compact('page_title', 'program_types', 'default_start_dt', 'default_end_dt', 'data_table', 'controller', 'academic_sessions', 'aca_ses', 'index_number'));
    }


    function print_export_report()
    {
        $auth_user = $this->Session->read('loginData');
        if ($auth_user['user_level'] != 'SRC') { //For SRC Only
            $this->redirect(array('controller' => 'Student', 'action' => 'index'));
        }

        $download = false;

        $_POST = $this->StudentUser->sanitize($_POST);

        $media_type = $_POST['data_type'];
        $start_dt = $_POST['data_start_dt'];
        $end_dt = $_POST['data_end_dt'];
        $index_number = $_POST['data_index_number'];
        $index_number = trim($index_number);
        $index_number_p = $index_number;
        if (empty($index_number)) {
            $index_number_p = null;
        }
        $aca_ses = $_POST['data_session'];

        //Get students ids with filters
        /* $conditions = array('StudentUser.program_id'=>$program_id);
         if($section != 'all'){
             $conditions['StudentUser.classification']=$section;
         }
         $stu_list = $this->StudentUser->find('all',array(
             'fields'=>array('StudentUser.id','StudentUser.index_number','StudentUser.program_id'),
             'conditions'=>$conditions,
             'recursive'=>-1
         ));
         $student_user_ids = array();
         foreach($stu_list as $dt){
             $student_user_ids[]=$dt['StudentUser']['id'];
         }*/
        $fee_type_id = 18; //SRC dues only

        $data_table = $this->_get_src_payments($start_dt, $end_dt, $fee_type_id, $aca_ses, $index_number_p);

        $this->autoLayout = false;

        if ($media_type == 'export') {
            if (!empty($data_table)) {
                $download = true;
            }
            $tl_paid = 0;
            $tl_fee_amount = 0;
            $tl_bal = 0;
            $t_body_data = array();
            foreach ($data_table as $obj) {

                $rows = array();

                $paid = doubleval($obj['tl_credit_amount']);
                $fee_amount = doubleval($obj['amount']);
                $bal = doubleval($obj['balance']);

                $tl_paid = $tl_paid + $paid;
                $tl_fee_amount = $tl_fee_amount + $fee_amount;
                $tl_bal = $tl_bal + $bal;

                $rows[] = $obj['date'];
                $rows[] = $obj['index_number'];
                $rows[] = $obj['name'];
                $rows[] = $this->formatNumber($obj['amount'], 'number');
                $rows[] = $this->formatNumber($obj['tl_credit_amount'], 'number');
                $rows[] = $this->formatNumber($obj['balance'], 'number');
                $rows[] = $obj['served'];
                $rows[] = $obj['served_date'];
                $t_body_data[] = $rows;

            }

            $rows = array();
            $rows[] = '';
            $rows[] = '';
            $rows[] = 'Total';
            $rows[] = $this->formatNumber($tl_fee_amount, 'number');
            $rows[] = $this->formatNumber($tl_paid, 'number');
            $rows[] = $this->formatNumber($tl_bal, 'number');
            $rows[] = '';
            $rows[] = '';
            $t_body_data[] = $rows;

            $list_data = $t_body_data;
            $list_headers = array('Date', 'Student ID', 'Details', 'Fee Amount GHc', 'Total Paid GHc', 'Balance GHc', 'Served', 'Served Date');
            $filename = 'SRC Report';
            $res = $this->convertToExcel($list_headers, $list_data, $filename);
            $objPHPExcel = $res['excel_obj'];
            $filename = $res['filename'];
        } elseif ($media_type == 'print') {
            $this->autoLayout = true;
            $this->layout = 'print_layout';
        }
        //$print_title = $table_title;
        $controller = $this;

        $this->set(compact('controller', 'download', 'print_title', 'table_title', 'data_table', 'fee_type', 'objPHPExcel', 'download', 'filename', 'media_type'));
    }


    function _get_src_payments($start_dt, $end_dt, $fee_type, $aca_ses, $index_no = null, $program = null)
    {
        $acc_ses_data = $this->AcademicSession->getAcademicSessionById($aca_ses);
        $acca_year = $this->current_academic_year;
        if (!empty($acc_ses_data)) {
            $acca_year = $acc_ses_data['AcademicSession']['acc_year'];
        }
        $condition_array = array('Transaction.trans_type' => 'fee_payment', 'Transaction.academic_session_id' => $aca_ses);
        $fee_condition = array('fee_type_id' => $fee_type, 'academic_year' => $acca_year);

        if ($index_no != null) {
            $student = $this->StudentUser->find('first', array(
                'fields' => array('StudentUser.id'),
                'conditions' => array('StudentUser.index_number' => $index_no),
                'recursive' => -1
            ));
            if ($student) {
                $condition_array['Transaction.student_user_id'] = $student['StudentUser']['id'];
            } else {
                $condition_array['Transaction.student_user_id'] = 0;
            }

            $fee_condition['index_number'] = $index_no;
        }

        $fee_ids = array();
        $fee_ids_data = $this->Fee->find('all', array(
            'fields' => array('id'),
            'conditions' => $fee_condition,
            'recursive' => -1
        ));
        foreach ($fee_ids_data as $d) {
            $fee_ids[] = $d['Fee']['id'];
        }


        if (!empty($start_dt) || !empty($end_dt)) {
            //'Order.order_date >=' => $start_dt, 'Order.order_date <=' => $end_dt
            if (!empty($start_dt) && empty($end_dt)) {
                $condition_array['DATE(Transaction.created) >='] = $start_dt;
                $condition_array['DATE(Transaction.created) <='] = $start_dt;
            } elseif (empty($start_dt) && !empty($end_dt)) {
                $condition_array['DATE(Transaction.created) >='] = date('Y-m-d'); //from now
                $condition_array['DATE(Transaction.created) <='] = $end_dt; //to a given end date
            } elseif (!empty($start_dt) && !empty($end_dt)) {
                $condition_array['DATE(Transaction.created) >='] = $start_dt; //from now
                $condition_array['DATE(Transaction.created) <='] = $end_dt; //to a given end date
                //$condition_array['Transaction.created >=']=$start_dt;//from now
                //$condition_array['Transaction.created <=']=$end_dt; //to a given end date
            }
        }

        //debug($condition_array);

        $contain = array(
            'TransactionItem' => array(
                'fields' => array('TransactionItem.id', 'TransactionItem.credit_amt', 'TransactionItem.fee_id', 'TransactionItem.transaction_id'),
                'conditions' => array('TransactionItem.fee_id' => $fee_ids),
                'Fee' => array(
                    'fields' => array('Fee.id', 'Fee.amount'),
                    'FeeType' => array('fields' => array('FeeType.id', 'FeeType.description'))
                ),
                'StudentSrcDue' => array(
                    'fields' => array('StudentSrcDue.id', 'StudentSrcDue.served', 'StudentSrcDue.served_date')
                )
            ),
            'StudentUser' => array('fields' => array('StudentUser.id', 'StudentUser.index_number', 'StudentUser.fname', 'StudentUser.mname', 'StudentUser.lname'))
        );
        $fields = array('Transaction.id', 'Transaction.created', 'Transaction.trans_type');
        $data_table = $this->Transaction->find('all', array(
            'fields' => $fields,
            'conditions' => $condition_array,
            'contain' => $contain,
            'order' => array("Transaction.id" => 'asc'),
            //'recursive' => 3
        ));

        $return = array();
        foreach ($data_table as $key => $value) {
            foreach ($value['TransactionItem'] as $trans) {
                // debug($trans);
                $trans['transaction_date'] = $value['Transaction']['created'];
                $trans['transaction_id'] = $value['Transaction']['id'];
                $fee_type_id = $trans['Fee']['fee_type_id'];
                /* if($fee_type != null){
                     if($fee_type != 'all'){ //After the query Now apply the fee type condition
                         if($fee_type_id != $fee_type){
                             continue;
                         }
                     }
                 }*/
                $stu_id = $value['StudentUser']['id'];
                $return[$stu_id]['stu_data'] = $value['StudentUser'];
                $return[$stu_id]['transactions'][$fee_type_id][] = $trans;
            }
        }

        //debug($return);

        $result = array();
        $ref_count = 1;
        foreach ($return as $key => $value) {
            foreach ($value['transactions'] as $trans) {
                $description = '';
                $amount = 0.00;
                $tl_credit_amount = 0.00;
                foreach ($trans as $trans_inner) {
                    $trans_ref = $trans_inner['transaction_id'];
                    $created = date("Y-m-d", strtotime($trans_inner['transaction_date']));
                    $description = $trans_inner['Fee']['FeeType']['description'];
                    $amount = doubleval($trans_inner['Fee']['amount']);
                    $tl_credit_amount = $tl_credit_amount + doubleval($trans_inner['credit_amt']);
                    if (empty($trans_inner['StudentSrcDue'])) {
                        $served = 'No';
                        $served_date = '';
                    } else {
                        $served = $trans_inner['StudentSrcDue']['served'];
                        $served_date = $trans_inner['StudentSrcDue']['served_date'];
                    }
                }
                $result[] = array(
                    'id' => $trans_ref,
                    'trans_item_id' => $trans_inner['id'],
                    'date' => $created,
                    'reference' => $ref_count,
                    'index_number' => $value['stu_data']['index_number'],
                    'name' => ucwords(strtolower($value['stu_data']['fname'] . ' ' . $value['stu_data']['mname'] . ' ' . $value['stu_data']['lname'])),
                    'description' => ucwords(strtolower($description)),
                    'amount' => $amount,
                    'tl_credit_amount' => $tl_credit_amount,
                    'balance' => $amount - $tl_credit_amount,
                    'served' => $served,
                    'served_date' => $served_date
                );
                $ref_count = $ref_count + 1;
            }
        }
        //debug($result);

        return $result;
    }


    function  update_service_request()
    {
        $this->autoRender = false;
        $this->autoLayout = false;
        $auth_user = $this->Session->read('loginData');
        if ($this->request->is('ajax')) {
            $_POST = $this->StudentUser->sanitize($_POST);
            $data = array('StudentSrcDue' => array(
                'transaction_item_id' => $_POST['id'],
                'served' => 'Yes',
                'created_by' => $auth_user['id'],
                'served_date' => date('Y-m-d H:i:s')

            ));
            $gdata = $this->StudentSrcDue->save($data['StudentSrcDue']);
            if ($gdata) {
                if ($_POST['id'] > 0) {
                    return json_encode(array('code' => 0, 'msg' => 'Data Saved!'));
                } else {
                    return json_encode(array('code' => 0, 'msg' => 'Data Saved', 'id' => $this->StudentSrcDue->id));
                }
            } else {
                return json_encode(array('code' => 1, 'msg' => __('Data cannot be saved')));
            }
        }
    }

}